package com.sky.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.sky.constant.StatusConstant;
import com.sky.entity.Dish;
import com.sky.entity.Orders;
import com.sky.entity.Setmeal;
import com.sky.entity.User;
import com.sky.mapper.DishMapper;
import com.sky.mapper.OrderMapper;
import com.sky.mapper.SetmealMapper;
import com.sky.mapper.UserMapper;
import com.sky.service.WorkspaceService;
import com.sky.vo.BusinessDataVO;
import com.sky.vo.DishOverViewVO;
import com.sky.vo.OrderOverViewVO;
import com.sky.vo.SetmealOverViewVO;
import io.swagger.models.auth.In;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
public class WorkspaceServiceImpl implements WorkspaceService {

    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private DishMapper dishMapper;
    @Autowired
    private SetmealMapper setmealMapper;

    /**
     * 根据时间段统计营业数据
     * @param begin
     * @param end
     * @return
     */
    @Override
    public BusinessDataVO getBusinessData(LocalDateTime begin, LocalDateTime end) {
        /**
         * 营业额：当日已完成订单的总金额
         * 有效订单：当日已完成订单的数量
         * 订单完成率：有效订单数 / 总订单数
         * 平均客单价：营业额 / 有效订单数
         * 新增用户：当日新增用户的数量
         */
        //查询总订单数
        LambdaQueryWrapper<Orders> wrapper = new LambdaQueryWrapper<>();
        wrapper.lt(Orders::getOrderTime, end).gt(Orders::getOrderTime, begin);
        int size = orderMapper.selectList(wrapper).size();
        Integer totalOrderCount = size;
        //有效订单数
        LambdaQueryWrapper<Orders> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.lt(Orders::getOrderTime, end).gt(Orders::getOrderTime, begin).eq(Orders::getStatus, Orders.COMPLETED);
        List<Orders> orders = orderMapper.selectList(lambdaQueryWrapper);
        Integer validOrderCount = orders.size();
        //营业额
        if (orders != null && orders.size() > 0) {
            BigDecimal turnover = BigDecimal.ZERO;
            for (Orders order : orders) {
                BigDecimal amount = order.getAmount();
                turnover = turnover.add(amount);
            }

            Double unitPrice = 0.0;

            Double orderCompletionRate = 0.0;
            if (totalOrderCount != 0 && validOrderCount != 0) {
                //订单完成率
                orderCompletionRate = validOrderCount.doubleValue() / totalOrderCount;
                //平均客单价
                unitPrice = turnover.doubleValue() / validOrderCount;
            }


            //新增用户数
            //查询当天总用户数
            QueryWrapper<User> wrapper1 = new QueryWrapper<>();
            wrapper1.lambda().lt(User::getCreateTime, end);
            Integer todayInteger = userMapper.selectCount(wrapper1);
            //查询前一天的用户总数
            QueryWrapper<User> beforeWrapper = new QueryWrapper<>();
            LocalDateTime beforeEndTime = LocalDateTime.of(LocalDate.now().plusDays(-1), LocalTime.MAX);
            beforeWrapper.lambda().lt(User::getCreateTime, beforeEndTime);
            Integer befortInteger = userMapper.selectCount(beforeWrapper);
            //计算变化的用户数
            Integer newUsers = todayInteger - befortInteger;
            return BusinessDataVO.builder()
                    .turnover(turnover.doubleValue())
                    .validOrderCount(validOrderCount)
                    .orderCompletionRate(orderCompletionRate)
                    .unitPrice(unitPrice)
                    .newUsers(newUsers)
                    .build();
        }
        return null;

    }


    /**
     * 查询订单管理数据
     *
     * @return
     */
    @Override
    public OrderOverViewVO getOrderOverView() {
        //待接单
        Integer waitingOrders = orderMapper.selectList(new LambdaQueryWrapper<Orders>()
                .eq(Orders::getStatus,Orders.TO_BE_CONFIRMED).between(Orders::getOrderTime,LocalDateTime.of(LocalDate.now(),LocalTime.MIN),
                        LocalDateTime.of(LocalDate.now(),LocalTime.MAX))).size();

        //待派送

        Integer deliveredOrders = orderMapper.selectList(new LambdaQueryWrapper<Orders>()
                .eq(Orders::getStatus,Orders.CONFIRMED).between(Orders::getOrderTime,LocalDateTime.of(LocalDate.now(),LocalTime.MIN),
                        LocalDateTime.of(LocalDate.now(),LocalTime.MAX))).size();

        //已完成

        Integer completedOrders = orderMapper.selectList(new LambdaQueryWrapper<Orders>()
                .eq(Orders::getStatus,Orders.COMPLETED).between(Orders::getOrderTime,LocalDateTime.of(LocalDate.now(),LocalTime.MIN),
                        LocalDateTime.of(LocalDate.now(),LocalTime.MAX))).size();

        //已取消

        Integer cancelledOrders = orderMapper.selectList(new LambdaQueryWrapper<Orders>()
                .eq(Orders::getStatus,Orders.CANCELLED).between(Orders::getOrderTime,LocalDateTime.of(LocalDate.now(),LocalTime.MIN),
                        LocalDateTime.of(LocalDate.now(),LocalTime.MAX))).size();

        //全部订单

        Integer allOrders = orderMapper.selectList(new LambdaQueryWrapper<Orders>()
                .between(Orders::getOrderTime,LocalDateTime.of(LocalDate.now(),LocalTime.MIN),
                        LocalDateTime.of(LocalDate.now(),LocalTime.MAX))).size();

            OrderOverViewVO o = OrderOverViewVO.builder()
                    .waitingOrders(waitingOrders)
                    .deliveredOrders(deliveredOrders)
                    .completedOrders(completedOrders)
                    .cancelledOrders(cancelledOrders)
                    .allOrders(allOrders)
                    .build();
            return o;
        }

    /**
     * 查询菜品总览
     *
     * @return
     */
    @Override
    public DishOverViewVO getDishOverView() {

        Integer sold = dishMapper.selectList(new LambdaQueryWrapper<Dish>().eq(Dish::getStatus,StatusConstant.ENABLE)).size();


        Integer discontinued = dishMapper.selectList(new LambdaQueryWrapper<Dish>().eq(Dish::getStatus,StatusConstant.DISABLE)).size();

        return DishOverViewVO.builder()
                .sold(sold)
                .discontinued(discontinued)
                .build();
    }

    /**
     * 查询套餐总览
     *
     * @return
     */
    @Override
    public SetmealOverViewVO getSetmealOverView() {

        Integer sold = setmealMapper.selectList(new LambdaQueryWrapper<Setmeal>().eq(Setmeal::getStatus,StatusConstant.ENABLE)).size();


        Integer discontinued = setmealMapper.selectList(new LambdaQueryWrapper<Setmeal>().eq(Setmeal::getStatus,StatusConstant.DISABLE)).size();

        return SetmealOverViewVO.builder()
                .sold(sold)
                .discontinued(discontinued)
                .build();
    }
}
